package com.nulldev.util.web.nTubeExtensions.Redwood;

import java.time.Duration;

import com.nulldev.util.JVM.Arguments;
import com.nulldev.util.JVM.JVM;
import com.nulldev.util.data.CachedItem;
import com.nulldev.util.data.variable;
import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.manage.experiments.Experiments;
import com.nulldev.util.web.HttpClient.HttpClient;
import com.nulldev.util.web.YouTubeExtractor.YouTubeExtractor;
import com.nulldev.util.web.YouTubeExtractor.signatures.SignatureExtractor;

public class Redwood {
	public static final boolean ENABLE_AUTO_UPDATING = Arguments.hasArgument("--Redwood.enableDynamicPatching");
	public static final boolean ENABLE_CAPTIONS = Experiments.get("ntube://redwood-captions-module/").isActive();
	public static final boolean ENABLE_REMOTE = ENABLE_AUTO_UPDATING && Arguments.hasArgument("--Redwood.enableCasting");
	public static final Logger log = LoggerFactory.getLogger();
	static {
		if (ENABLE_AUTO_UPDATING) {
			log.info("[Redwood] Enabled auto-patching.");
		}
		if (ENABLE_CAPTIONS) {
			log.info("[Redwood] Enabled captions.");
		}
		if (ENABLE_REMOTE) {
			log.info("[Redwood] Enabled casting support.");
		}
	}
	public static final variable<String> player_url = new variable<String>();
	public static final CachedItem<String> player = new CachedItem<String>("YTE_REDWOOD_PLAYER", Long.MAX_VALUE, !ENABLE_AUTO_UPDATING) {

		@Override
		public String accquire() throws Exception {
			String playerURL;
			if (SignatureExtractor.hasCachedPlayerURL()) {
				playerURL = SignatureExtractor.getCachedPlayerURL();
			} else {
				YouTubeExtractor.extractor.getAuto();
				playerURL = SignatureExtractor.getCachedPlayerURL();
			}
			player_url.set(playerURL);
			return RedwoodAutoUpdater.process(HttpClient.getString().url(playerURL).timeout(Duration.ofSeconds(60)).create().dataThenClose());
		}

	};

	public static void main(String[] args) throws Exception {
		player.getAuto();
		JVM.println(player.get());
	}
}
